<?php

namespace App\Exports\Invoice;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromArray;

class InvoiceExport implements FromArray
{

    public Collection $originalData;
    public array      $excelHeaders;
    public array      $excelContents = [];

    public function __construct(Collection $originalData)
    {
        $this->originalData = $originalData;
    }

    public function array(): array
    {
        // TODO: Implement array() method.
        $this->generateExcelHeader();
        $this->originalData->each(
            function ($item) {
                array_push(
                    $this->excelContents, [
                        $item['shopCode'],
                        $item['shopName'],
                        $item['addressPrefix'],
                        $item['blueInvoiceTime'],
                        "\t" . $item['blueInvoiceNumber'],
                        $item['statusText'],
                        $item['invoiceTypeText'],
                        $item['channelText'],
                        $item['invoiceTitle'],
                        $item['headerTypeText'],
                        $item['blueTaxValueTotal'],
                        "\t" . implode(PHP_EOL, array_column($item['businessInfo'], 'businessId')),
                        implode(PHP_EOL, array_column($item['businessInfo'], 'createdAt')),
                        implode(PHP_EOL, array_column($item['businessInfo'], 'totalInvoiceAmount')),
                        $item['applyName'],
                        $item['operatorName'],
                    ]
                );
            }
        )->values()->toArray();
        return collect(
            [$this->excelHeaders]
        )->merge($this->excelContents)->toArray();
    }


    public function generateExcelHeader()
    {
        $this->excelHeaders = [
            '门店编号',
            '门店名称',
            '省市区',
            '开票时间',
            '发票号码',
            '开票状态',
            '发票类型',
            '开票渠道',
            '抬头类型',
            '发票抬头',
            '开票金额',
            '订货单号',
            '下单时间',
            '实付金额',
            '申请人',
            '操作人'
        ];
    }
}
